// src/components/Aij/index.vue
<template>
	<el-dialog v-if="aijShow" 
		:visible.sync="aijShow" 
		:close-on-click-modal="false"
		:modal="false"
		:show-close="false"
		class="aij-chat">
		<el-scrollbar ref="aij-msgs" :style="{height:'25px'}">
			<div v-for="msg in aijMsgs" 
				class="msg-item" 
				:class="msgClass(msg.type)"
				v-html="msg.msg">
			</div>
		</el-scrollbar>
	    <template #footer>
	      <div class="dialog-footer">
			  <el-form :model="aijChat">
			  <el-row>
				  <el-col :span="3" align="left">
					<el-button @click="openVideo">视频</el-button>
				  </el-col>
				  <el-col :span="18">
					<el-popover
					  ref="aij-pop"
					  placement="top"
					  title=""
					  trigger="manual"
					  :value="aijChat.pop.visible"
					  popper-class="aij-pop">
					  <el-select v-if="aijChat.pop.select" v-model="aijChat.pop.selected" popper-class="aij-pop" clearable>
						  <el-option
							v-for="item in aijChat.pop.select"
							:label="item.label"
							:value="item.value">
						  </el-option>
					  </el-select>
					  <el-checkbox v-for="item in aijChat.pop.checkbox" :label="item.value" v-model="item.checked">
						{{item.label}}
					  </el-checkbox>
					  <el-radio-group v-model="aijChat.pop.selected">
					  <el-radio v-for="item in aijChat.pop.radio" :label="item.value">
						{{item.label}}
					  </el-radio>
					  </el-radio-group>
					  <el-input ref="aij-msg" 
						v-model="aijChat.msg" 
						:type="aijChat.type" 
						:placeholder="aijChat.placeholder" 
						:refer="aijChat.refer" 
						slot="reference"/>
					</el-popover>
				  </el-col>
				  <el-col :span="3">
					  <el-button @click="sendMsg">发送</el-button>
				  </el-col>
			  </el-row>
			  </el-form>
	      </div>
	    </template>
	</el-dialog>
</template>

<script>
export default {
  data() {
    return {
      aijShow: true,
	  aijChat: {
		msg: '你好',
		type: 'text',
		refer: '',
		placeholder: '请输入消息',
		pop: {},
		word: ''
	  },
	  aijMsgs: [],
	  aijConf: {
		  wsServer: 'ws://192.168.0.101:9001/ws',
		  wsAccount: '',
		  wsSecret: '',
		  pushServer: 'ws://192.168.0.101:2700',
		  liveServer: 'http://192.168.0.101:8080/live/',
		  liveDelay: 2500,
	  },
	  wsClient: null,
	  sessionId: this.$genUUID(),
	  liveClient: null,
	  flvPlayer: null,
	  flvAudio: null,
    };
  },
  mounted() {
	window.clickMsg = this.clickMsg;
    this.aijShow = true;
	var that = this;
	//等待页面渲染完成
	setTimeout(function(){
		that.checkLogin();
	}, 1000);
  },
  methods: {
	msgClass(type) {
		return `msg-${type}`;
	},
	msgScroll () {
		//$("#msg-div").height($("#msg-div div:last").height() - 4);
		const ele = this.$refs['aij-msgs'].wrap;
		ele.scrollTop = ele.scrollHeight;
	},
	//连接服务
	connWs(wsServer, onSucess = null, onError = null) {
		var that = this;
		var client = new this.$WsClient({
			login: this.aijConf.wsAccount,
			passwd: this.aijConf.wsSecret,
			socketUrl: this.aijConf.wsServer,
			sessid: this.sessionId,
			onmessage: function(e) {
				that.handleMsg(e.eventData);
			},
			onWSConnect: function(o) {
				client.call('login', {});
				if (onSucess) onSucess();
			},
			onWSLogin: function(success) {
			},
			onWSError: function(e) {
				if (onError) onError(e);
			},
			onWSClose: function(success) {
			}
		});
		return client;
	},
	//检查登录
	checkLogin() {
		if (document.querySelector('.avatar-container')) {
			this.initMsg('我已成功登录会员');
		} else {
			this.initMsg('你好');
		}
		this.sendMsg();
	},
	//初始化消息
	initMsg(msg) {
		this.aijChat.pop = {visible: false};
		this.$refs['aij-msg'].focus();
		this.aijChat.refer = '';
		this.aijChat.type = 'text';
		this.aijChat.placeholder = '请输入消息';
		this.aijChat.msg = msg;
	},
	//处理消息
	procMsg(msg, txt = '') {
		var pattern = /[，。！？：；、,.!?:;]/;
		var msgs = msg.split(pattern);
		if (msgs.length <= 1) return;
		var txts = txt.split(pattern);
		msgs[0] = txts[txts.length - 1] + msgs[0];
		var len = msgs.length;
		for (var i = 0; i < len - 1; i++) {
			var sub = msgs[i] + ",";
			//console.log(sub);
			if (this.liveClient) {
				var params = {
					body: sub
				};
				this.liveClient.call("message", params, function(e) {
				}, function(e) {
				});
			}
		}
	},
	//点击消息
	clickMsg(obj) {
		var txt = obj.innerText;
		var ele = document.querySelector('[aij="' + txt + '"]');
		if (ele) {
			var tagName = ele.tagName.toLowerCase();
			var tagType = ele.getAttribute('type');
			if (tagName == 'a' || tagName == 'span' || tagName == 'button' || (tagName == 'input' && tagType == "button")) {
				ele.click();
				//if ($('.layui-layer-dialog').length > 0 && $('.layui-layer-dialog .layui-icon-success').length == 0) return;
				this.initMsg('我要' + txt);
				this.sendMsg();
			} else if (tagName == 'form') {
				this.initMsg('我要' + txt);
				this.sendMsg();
			} else if (tagName == 'input') {
				this.aijChat.pop = '';
				this.aijChat.type = tagType;
				this.aijChat.msg = ele.value;
				this.aijChat.refer = txt;
				this.aijChat.placeholder = '请' + txt;
				this.$refs['aij-msg'].focus();
			} else if (tagName == 'label' || tagName == 'div') {
				var clsName = ele.getAttribute('class');
				if (clsName.indexOf("el-radio") >= 0) {
					tagType = 'radio';
				} else if (clsName.indexOf("el-checkbox") >= 0) {
					tagType = 'checkbox';
				} else if (clsName.indexOf("el-select") >= 0) {
					tagType = 'select';
				} else if (clsName.indexOf("el-input-number") >= 0) {
					tagType = 'number';
				}
				if (tagType == "radio" || tagType == "checkbox") {
					var content = {
						visible: true,
						selected: null,
						select: null,
						radio: null,
						checkbox: null
					};
					var items = [];
					var eles = document.querySelectorAll('[aij="' + txt + '"]');
					eles.forEach(function(e) {
						var label = e.querySelector('.el-' + tagType + '__label');
						var checked = e.getAttribute('class').indexOf('is-checked') >= 0;
						var input = e.querySelector('input');
						items.push({
							label: label.innerText,
							checked: checked,
							value: input.value
						});
						if (tagType == "radio" && checked) {
							content.selected = input.value;
						}
					});
					if (tagType == "radio") {
						content.radio = items;
					} else if (tagType == "checkbox") {
						content.checkbox = items;
					} else {
						content.visible = false;
					}
					//console.log(content);
					this.aijChat.pop = content;
				} else if (tagType == "select") {
					var selected = null;
					var input = ele.querySelector('input');
					var options = [];
					var eles = ele.querySelectorAll('li.el-select-dropdown__item');
					eles.forEach(function(e, i) {
						options.push({
							label: e.innerText,
							value: i
						});
						if (input.value == e.innerText) selected = i;
					});
					var content = {
						visible: true,
						selected: selected,
						select: options,
						radio: null,
						checkbox: null
					};
					this.aijChat.pop = content;
				} else if (tagType == "number") {
					this.aijChat.pop = '';
					this.aijChat.type = tagType;
					var input = ele.querySelector('input');
					this.aijChat.msg = input.value;
				}
				this.aijChat.refer = txt;
				this.aijChat.placeholder = '请' + txt;
				this.$refs['aij-msg'].focus();
			}
		}
	},
	//解析消息
	parseMsg(msg) {
		if (msg.indexOf(']') >= 0) {
			msg = msg.replaceAll('[', '<a href="javascript:;" onclick="clickMsg(this)">');
			msg = msg.replaceAll(']', '</a>');
		}
		return msg;
	},
	//接收消息
	recvMsg(msg, id) {
		var msgHead = "<b>AI：</b>";
		var idMsg = null;
		this.aijMsgs.forEach(function (aijMsg) {
		    if (aijMsg.id === id) {
		        idMsg = aijMsg;
				return;
		    }
		});
		if (idMsg) {
			var txt = idMsg.msg;
			idMsg.msg = txt + msg;
			this.procMsg(msg, txt);
		} else {
			idMsg = {
				  id: id,
				  type: 'you',
				  msg: msgHead + msg,
			};
			this.aijMsgs.push(idMsg);
			this.procMsg(idMsg.msg);
		}
		if (msg == '') {
			var txt = idMsg.msg;
			idMsg.msg = this.parseMsg(txt);
			//this.saveMsg(txt, 'aij', 0);
		}
		this.msgScroll();
		if (msg == '' && idMsg.msg.endsWith('登录会员完成。')) {
			var that = this;
			//等待页面渲染完成
			setTimeout(function(){
				that.checkLogin();
			}, 1000);
		}
	},
	//处理消息
	handleMsg(data) {
		if (data.method == "message") {
			this.recvMsg(data.params.body, data.id);
		}
		if (data.method == "word") {
			setTimeout(function() {
				this.aijChat.word = data.params.body;
			}, liveDelay);
		}
	},
	//发送消息
	sendMsg() {
		if (!this.wsClient) {
			var that = this;
			this.wsClient = this.connWs(this.wsServer, function(e) {
				that.sendMsg();
			}, function(e) {
				that.wsClient = that.connWs(that.wsServer);
			});
			return;
		}
		var refer = this.aijChat.refer;
		if (refer) {
			var ele = document.querySelector('[aij="' + refer + '"]');
			var tagName = ele.tagName.toLowerCase();
			var clsName = ele.getAttribute('class');
			if (clsName.indexOf("el-radio") >= 0) {
				tagName = 'radio';
			} else if (clsName.indexOf("el-checkbox") >= 0) {
				tagName = 'checkbox';
			} else if (clsName.indexOf("el-select") >= 0) {
				tagName = 'select';
			} else if (clsName.indexOf("el-input-number") >= 0) {
				tagName = 'number';
			}
			if (this.aijChat.pop) {
				if (tagName == 'select') {
					var selected = this.aijChat.pop.selected;
					var input = ele.querySelector('input');
					if (selected != null && selected !== '') {
						ele.click();
						//注意设置popper-append-to-body为false
						var eles = ele.querySelectorAll('li.el-select-dropdown__item');
						eles[selected].click();
						input.dispatchEvent(new Event('change'));
					} else {
						//暂时无法同步数据，待修改
						input.value = '';
						input.dispatchEvent(new Event('clear'));
					}
				} else {
					var selected = this.aijChat.pop.selected;
					var pops = tagName == 'radio' ? this.aijChat.pop.radio : this.aijChat.pop.checkbox;
					var eles = document.querySelectorAll('[aij="' + refer + '"]');
					eles.forEach(function(e, i) {
						var el = e.querySelector('.el-' + tagName + '__input');
						var input = el.querySelector('input');
						if (tagName == 'radio') {
							var value = pops[i].value;
							var checked = (value == selected);
							if (checked) {
								e.click();
								//必须手动触发事件同步
								input.dispatchEvent(new Event('change'));
								return;
							}
						} else {
							var checked = pops[i].checked;
							if (checked) {
								e.className += ' is-checked';
								el.className += ' is-checked';
							} else {
								e.className = e.className.replace(' is-checked', '');
								el.className = el.className.replace(' is-checked', '');
							}
							input.checked = checked;
							//必须手动触发事件同步
							input.dispatchEvent(new Event('change'));
						}
					});
				}
			} else if (tagName == 'number') {
				var input = ele.querySelector('input');
				input.value = this.aijChat.msg;
				//必须手动触发事件同步
				input.dispatchEvent(new Event('input'));
			} else {
				ele.value = this.aijChat.msg;
				//必须手动触发事件同步
				ele.dispatchEvent(new Event('input'));
			}
			this.initMsg('我已' + refer);
		}
		if (!this.aijChat.msg) {
			this.$refs['aij-msg'].focus();
			return;
		}
		var params = {
			body: this.aijChat.msg
		};
		var webClient = this.wsClient.socketReady() ? this.wsClient : this.liveClient;
		if (webClient) {
			var that = this;
			webClient.call("message", params, function(e) {
				var msgHead = "<b>我：</b>";
				var msg = {
					  type: 'me',
					  msg: msgHead + that.aijChat.msg,
				};
				that.aijMsgs.push(msg);
				that.aijChat.msg = '';
				that.msgScroll();
			}, function(e) {
			});
		}
	},
	//保存消息
	saveMsg(msg, from, count, self) {
	},
	//加载消息
	loadMsg(from) {
	},
	//显示消息
	showMsg() {
	},
	//视频开关
	openVideo() {
	  
	}
  }
};
</script>

<style>
.aij-chat {
	pointer-events: none;
	z-index: 4000 !important;
}
.aij-pop {
	z-index: 4001 !important;
}
.aij-chat .el-dialog {
	pointer-events: auto;
	position: absolute;
	left: 25%;
	top: auto;
	bottom: 0px;
}
.aij-chat .el-dialog__header {
	display: none;
}
.aij-chat .el-dialog__body {
	padding: 10px;
}
.aij-chat .el-dialog__footer {
	padding: 10px;
}
.aij-chat .el-scrollbar__wrap
{
  overflow-x: hidden;
}
.aij-chat .msg-item {
	display: flex;
	align-items: center;
	height: 10px;
	margin: 10px;
	text-align: center;
	border-radius: 4px;
	background: var(--el-color-primary-light-9);
	color: var(--el-color-primary);
}
.aij-chat .msg-item a {
	color: blue;
}
.aij-chat .msg-me {
	justify-content: left;
}
.aij-chat .msg-you {
	justify-content: right;
}
</style>
